//
//  TagController.swift
//  hello
//
//  Created by 赵康 on 2024/11/17.
//

import Vapor
import Fluent
import Redis

struct TagController: RouteCollection {
	private let cacheKeyPrefix = "tag:"
	private let cacheDuration: TimeAmount = .minutes(30)
	
	func boot(routes: RoutesBuilder) throws {
		let tags = routes.grouped("\(RouteEnum.tags.rawValue)")
		tags.post("\(RouteEnum.create.rawValue)", use: create)
		let protected = tags.grouped(AuthMiddleware())
		protected.get("\(RouteEnum.fetch.rawValue)", use: fetch)
	}
	
	@Sendable
	func fetch(req: Request) async throws -> [TagResponse] {
    let cacheKey = CacheConfig.KeyBuilder.tags()
		
		do {
				// 尝试从缓存中获取标签
			if let cachedTags = try await req.redis.get(cacheKey, asJSON: [TagResponse].self) {
				return cachedTags
			}
			
				// 如果缓存中没有，从数据库获取
			let tags = try await Tag.query(on: req.db)
				.filter(\.$isDeleted == false)
				.sort(\.$name, .ascending)
				.all()
			
			let tagResponses = tags.map { tag in
				TagResponse(id: tag.id, name: tag.name)
			}
			
				// 将结果存入缓存
			try await req.redis.setex(cacheKey,
																toJSON: tagResponses,
																expirationInSeconds: Int(cacheDuration.nanoseconds / 1_000_000_000))
			
			return tagResponses
		} catch {
			throw Abort(.internalServerError, reason: "无法获取标签")
		}
	}
	@Sendable
	func create(req: Request) async throws -> BasicResponse {
		let input = try req.content.decode(Tag.Create.self)
		if (try await Tag.query(on: req.db)
			.filter(\.$name == input.name)
			.first()) != nil {
			throw Abort(.conflict, reason: "标签已存在")
		}
		let tag = Tag(
			name: input.name,
			isDeleted: false,
			createdAt: Date(),
			updatedAt: Date()
		)
		try await tag.save(on: req.db)
    
    let tagPattern = "\(CacheConfig.Prefix.make(.album))*tags*"
    try await req.cache.batchDelete(forPattern: tagPattern, on: req.redis)
    
		return BasicResponse(success: true, message: "标签创建成功")
	}
}
